<template>
	<view>
		<scroll-view id="scrollView" scroll-y="true" :scroll-top="scrollTop"
		:scroll-with-animation="true"
		:style="{'height': style.contentH + 'px'}">
			<!-- 聊天列表 -->
			<block v-for="(item, index) in list" :key="index">
				<user-chat-list :item="item"></user-chat-list>
			</block>
		</scroll-view>
		<!-- 输入框 -->
		<user-chat-bottom @submit="submit"></user-chat-bottom>
	</view>
</template>

<script>
	import userChatBottom from '../../components/user-chat/user-chat-bottom.vue'
	import time from '../../common/time.js'
	import userChatList from '../../components/user-chat/user-chat-list.vue'
	export default {
		data() {
			return {
				scrollTop: 0,
				list: [],
				style: {
					contentH: 0,
					itemH: 0,
				}
			}
		},
		components: {
			userChatBottom,
			userChatList,
		},
		onLoad() {
			this.getData()
			this.initData()
			// let s1 = '1554970014'
			// let s2 = '1555146414'
			// console.log(time.gettime.gettime(s1))
			// console.log(time.gettime.gettime(s2))
			// console.log(time.gettime.gettime('1608809567'))
		},
		onReady() {
			this.pageToBottom()
		},
		methods: {
			initData() { // 初始化数据
				try {
					// API -> 设备 -> 系统信息
					const res = uni.getSystemInfoSync()
					this.style.contentH = res.windowHeight - uni.upx2px(120)
				} catch (e) {
					// error
				}
			},
			pageToBottom() { // 获取页面触底事件（主要是为了发送信息时滚动条能自动变化触底）
				let q = uni.createSelectorQuery()
				q.select('#scrollView').boundingClientRect()
				q.selectAll('.user-chat-item').boundingClientRect()
				
				q.exec((res) => {
					res[1].forEach((ret) => {
						this.style.itemH += ret.height
					})
					
					if (this.style.itemH > this.style.contentH) {
						this.scrollTop = this.style.itemH
					}
				})
			},
			getData() { // 获取聊天数据
				let arr = [
					{
						isme:false,
						userpic: '../../static/images/bg1.png',
						type: 'text',
						data: '哈哈',
						time: '1554970014', // 存入时间戳，可以动态转换时间
					},
					{
						isme:true,
						userpic: '../../static/common/add-input.png',
						type: 'img',
						data: '../../static/logo.png',
						time: '1554970012', // 存入时间戳，可以动态转换时间
					},
				]
				arr.forEach((item, index) => {
					item.gstime = time.gettime.getChatTime(item.time, index > 0 ? arr[index-1].time : 0)
				})
				this.list = arr
			},
			submit(data) { // 发送逻辑
				// 构建数据
				let now = new Date().getTime()
				let obj = {
					isme: true,
					userpic: '../../static/images/bg1.png',
					type: 'text',
					data: data,
					time: now,
					gstime: time.gettime.getChatTime(now, this.list[this.list.length - 1].time)
				}
				this.list.push(obj)
				this.pageToBottom()
			}
		}
	}
</script>

<style lang="scss" scoped>
</style>
